package com.fadadianqi.logistics.admin.printer;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

public class EthernetPrinter {

    private static final String PRINTER_CHARSET = "GBK";

    public static void main(String[] args) throws Exception {
        EthernetPrinter p = new EthernetPrinter("192.168.1.254", 9100);
        p.printBarCode("123456");
        p.println("123456");
        p.finish();
    }

    private String ipaddress;

    private int port;

    private Socket client = new java.net.Socket();

    private PrintWriter socketWriter;

    public EthernetPrinter(String ipaddress, int port) throws Exception {
        this.ipaddress = ipaddress;
        this.port = port;
        try {
            init();
        } catch (IOException e) {
            throw new Exception(e.toString());
        }
    }

    public void printBarCode(String barcode) {
        socketWriter.write(0x1d);
        socketWriter.write(0x68);
        socketWriter.write(120);
        socketWriter.write(0x1d);
        socketWriter.write(0x48);
        socketWriter.write(0x01);
        socketWriter.write(0x1d);
        socketWriter.write(0x6B);
        socketWriter.write(0x02);
        socketWriter.println(barcode);
        socketWriter.write(0x00);
    }

    private void init() throws IOException {
        client.connect(new InetSocketAddress(ipaddress, port), 9000);
        OutputStreamWriter osw = new OutputStreamWriter(client.getOutputStream(), PRINTER_CHARSET);
        socketWriter = new PrintWriter(osw);// 创建输入输出数据流// 创建一个 socket
    }

    public void print(String content) throws Exception {
        socketWriter.print(content);
    }

    public void println(String content) throws Exception {
        socketWriter.println(content);
    }

    public void zoomIn() {
        socketWriter.write(0x1c);
        socketWriter.write(0x21);
        socketWriter.write(12);
        socketWriter.write(0x1b);
        socketWriter.write(0x21);
        socketWriter.write(12);
    }

    public void zoomOut() {
        socketWriter.write(0x1c);
        socketWriter.write(0x21);
        socketWriter.write(2);
        socketWriter.write(0x1b);
        socketWriter.write(0x21);
        socketWriter.write(2);
    }

    public void finish() {
        try {
            socketWriter.flush();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
